﻿using Dapper;
using Inventorycount.API.Read.Application.Command;
using Inventorycount.Domain;
using Inventorycount.Dto;
using Inventorycount.ErrorCode;
using MediatR;
using System.Data;
using System.Text;

namespace Inventorycount.API.Read.Application.CommandHandLer
{
    public class GetLogCommandHandLer : IRequestHandler<GetLogCommand, APIPaing<LogDto>>
    {

        private readonly IDbConnection repository;

        public GetLogCommandHandLer(IDbConnection repository)
        {
            this.repository = repository;
        }
        public async Task<APIPaing<LogDto>> Handle(GetLogCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaing<LogDto>
            {
                Code = ResultCode.Ok,
                Message = "查询成功",
                Data = new List<LogDto>()
            };

            try
            {
                // 构建基础查询
                var sql = new StringBuilder(@"
                   SELECT 
                    o.Id,
                    o.Transfer_id,
                    o.Operation_desc,
                    o.Operation_type,
                    o.operation_time,
                    o.operator_id,
                    d.Id AS Id,
                    d.Name
                FROM Wms_Operation_log o
                JOIN Wms_User d ON o.operator_id = d.Id
                WHERE o.Transfer_id =o.Transfer_id");

                var parameters = new DynamicParameters();
                // 3. 修正分页查询
                sql.Append(" ORDER BY o.Id DESC");
                sql.Append(" LIMIT @Offset, @PageSize");
                parameters.Add("Offset", (request.PageIndex - 1) * request.PageSize);
                parameters.Add("PageSize", request.PageSize);
                // 4. 修正COUNT查询
                var countSql = new StringBuilder(@"
            SELECT COUNT(DISTINCT p.Id) 
            FROM Wms_Operation_log p
            JOIN Wms_User d ON p.Transfer_id = d.Id");

                // 执行查询
                var count = await repository.ExecuteScalarAsync<int>(countSql.ToString(), parameters);

                // 执行查询
                var log = await repository.QueryAsync<LogDto>(sql.ToString(), parameters);
             
                result.Data = log.ToList();
                result.TotalCount = count;
                result.TotalPage = (int)Math.Ceiling(count * 1.0 / request.PageSize);
                result.Message = "查询成功";
            }
            catch (Exception ex)
            {
                result.Code = ResultCode.Fail;
                result.Message = $"查询失败: {ex.Message}";
            }

            return result;
        }
    }
}
